//
//  TestWidgetExtension.swift
//  TestWidgetExtension
//
//  Created by 计海峰 on 2021/12/3.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

//  https://www.jianshu.com/p/94a98c203763
//  https://www.jianshu.com/p/bbc6a95d9c54

import WidgetKit
import SwiftUI
import Intents

struct Provider: IntentTimelineProvider {
    // 占位视图
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), configuration: ConfigurationIntent())
    }

    // 编辑屏幕在左上角选择添加Widget、第一次展示时会调用该方法
    // 为了在小部件库中显示小部件，WidgetKit要求提供者提供预览快照，在组件的添加页面可以看到效果
    func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), configuration: configuration)
        completion(entry)
    }

    // 进行数据的预处理，转化成Entry
    // 在这个方法内可以进行网络请求，拿到的数据保存在对应的entry中，调用completion之后会到刷新小组件
    func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []

        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate, configuration: configuration)
            entries.append(entry)
        }

        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
}

// 渲染 Widget 所需的数据模型，需要遵守TimelineEntry协议。
struct SimpleEntry: TimelineEntry {
    let date: Date
    let configuration: ConfigurationIntent
}

// 屏幕上 Widget 显示的内容，可以针对不同尺寸的 Widget 设置不同的 View。
struct TestWidgetExtensionEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        VStack {
            Text(entry.date, style: .time)
            Text(entry.date, style: .time)
        }
    }
}

// @main 主入口
@main
struct TestWidgetExtension: Widget {
    let kind: String = "TestWidgetExtension"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
            TestWidgetExtensionEntryView(entry: entry)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
    }
}

struct TestWidgetExtension_Previews: PreviewProvider {
    static var previews: some View {
        TestWidgetExtensionEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent()))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}
